<template>
  <div class="help-detail">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button @click="handleBack" :icon="ArrowLeft" circle />
        <div class="breadcrumb">
          <el-breadcrumb separator=">">
            <el-breadcrumb-item :to="{ path: '/help' }">帮助中心</el-breadcrumb-item>
            <el-breadcrumb-item>{{ article.category }}</el-breadcrumb-item>
            <el-breadcrumb-item>{{ article.title }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="placeholder"></div>
      </div>

      <!-- 文章内容 -->
      <div class="article-container">
        <el-card class="article-card">
          <!-- 文章头部信息 -->
          <div class="article-header">
            <div class="article-meta">
              <el-tag :type="getCategoryType(article.category)">{{ article.category }}</el-tag>
              <span class="publish-date">发布时间：{{ formatDate(article.createdAt) }}</span>
              <span class="update-date">更新时间：{{ formatDate(article.updatedAt) }}</span>
              <span class="view-count">阅读 {{ article.viewCount }} 次</span>
            </div>
            
            <h1 class="article-title">{{ article.title }}</h1>
            
            <div class="article-summary" v-if="article.summary">
              <p>{{ article.summary }}</p>
            </div>
          </div>

          <!-- 文章正文 -->
          <div class="article-content">
            <div v-html="article.content"></div>
          </div>

          <!-- 文章底部操作 -->
          <div class="article-footer">
            <div class="rating-section">
              <h4>这篇文章对您有帮助吗？</h4>
              <div class="rating-buttons">
                <el-button 
                  :type="userRating === 'helpful' ? 'primary' : 'default'"
                  @click="rateArticle('helpful')"
                  :loading="rating"
                >
                  <el-icon><ThumbsUp /></el-icon>
                  有帮助 ({{ article.helpfulCount }})
                </el-button>
                <el-button 
                  :type="userRating === 'unhelpful' ? 'danger' : 'default'"
                  @click="rateArticle('unhelpful')"
                  :loading="rating"
                >
                  <el-icon><ThumbsDown /></el-icon>
                  没帮助 ({{ article.unhelpfulCount }})
                </el-button>
              </div>
            </div>

            <div class="share-section">
              <h4>分享给朋友</h4>
              <div class="share-buttons">
                <el-button @click="shareArticle('copy')" :icon="DocumentCopy">复制链接</el-button>
                <el-button @click="shareArticle('email')" :icon="Message">邮件分享</el-button>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 相关文章 -->
        <el-card class="related-articles" v-if="relatedArticles.length > 0">
          <template #header>
            <h3>相关文章</h3>
          </template>
          
          <div class="related-list">
            <div
              v-for="related in relatedArticles"
              :key="related.id"
              class="related-item"
              @click="goToArticle(related.id)"
            >
              <div class="related-content">
                <h4>{{ related.title }}</h4>
                <p>{{ related.summary }}</p>
                <div class="related-meta">
                  <el-tag size="small" :type="getCategoryType(related.category)">
                    {{ related.category }}
                  </el-tag>
                  <span class="related-views">{{ related.viewCount }} 次查看</span>
                </div>
              </div>
              <el-icon class="related-arrow"><ArrowRight /></el-icon>
            </div>
          </div>
        </el-card>

        <!-- 意见反馈 -->
        <el-card class="feedback-card">
          <template #header>
            <h3>意见反馈</h3>
          </template>
          
          <div class="feedback-content">
            <p>如果这篇文章没有解决您的问题，您可以：</p>
            <div class="feedback-actions">
              <el-button @click="contactSupport" type="primary">
                <el-icon><ChatDotRound /></el-icon>
                联系在线客服
              </el-button>
              <el-button @click="submitFeedback">
                <el-icon><EditPen /></el-icon>
                提交反馈建议
              </el-button>
              <el-button @click="viewMoreHelp">
                <el-icon><QuestionFilled /></el-icon>
                查看更多帮助
              </el-button>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 反馈弹窗 -->
    <el-dialog v-model="showFeedbackDialog" title="提交反馈建议" width="600px">
      <el-form ref="feedbackFormRef" :model="feedbackForm" :rules="feedbackRules" label-width="80px">
        <el-form-item label="反馈类型" prop="type">
          <el-select v-model="feedbackForm.type" placeholder="请选择反馈类型">
            <el-option label="内容错误" value="content_error" />
            <el-option label="内容过时" value="content_outdated" />
            <el-option label="内容不全" value="content_incomplete" />
            <el-option label="其他建议" value="other" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="详细描述" prop="content">
          <el-input
            v-model="feedbackForm.content"
            type="textarea"
            :rows="4"
            placeholder="请详细描述您的问题或建议"
          />
        </el-form-item>
        
        <el-form-item label="联系方式" prop="contact">
          <el-input
            v-model="feedbackForm.contact"
            placeholder="请输入邮箱或手机号（可选）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showFeedbackDialog = false">取消</el-button>
        <el-button type="primary" @click="submitFeedbackForm" :loading="submittingFeedback">
          提交反馈
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  ArrowRight,
  ThumbsUp,
  ThumbsDown,
  DocumentCopy,
  Message,
  ChatDotRound,
  EditPen,
  QuestionFilled
} from '@element-plus/icons-vue'
import dayjs from 'dayjs'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(true)
const rating = ref(false)
const submittingFeedback = ref(false)
const showFeedbackDialog = ref(false)
const userRating = ref(null)

// 文章数据
const article = ref({
  id: '',
  title: '',
  content: '',
  summary: '',
  category: '',
  viewCount: 0,
  helpfulCount: 0,
  unhelpfulCount: 0,
  createdAt: '',
  updatedAt: ''
})

const relatedArticles = ref([])

// 反馈表单
const feedbackFormRef = ref()
const feedbackForm = reactive({
  type: '',
  content: '',
  contact: ''
})

const feedbackRules = {
  type: [
    { required: true, message: '请选择反馈类型', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入反馈内容', trigger: 'blur' },
    { min: 10, message: '反馈内容至少10个字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm')
}

// 获取分类标签类型
const getCategoryType = (category) => {
  const typeMap = {
    '账户问题': 'primary',
    '订单问题': 'success',
    '支付问题': 'warning',
    '服务问题': 'info',
    '其他问题': 'default'
  }
  return typeMap[category] || 'default'
}

// 返回上一页
const handleBack = () => {
  router.go(-1)
}

// 跳转到文章
const goToArticle = (articleId) => {
  router.push(`/help/${articleId}`)
}

// 文章评分
const rateArticle = async (type) => {
  if (userRating.value === type) {
    ElMessage.info('您已经评价过了')
    return
  }

  try {
    rating.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    if (type === 'helpful') {
      article.value.helpfulCount++
      if (userRating.value === 'unhelpful') {
        article.value.unhelpfulCount--
      }
    } else {
      article.value.unhelpfulCount++
      if (userRating.value === 'helpful') {
        article.value.helpfulCount--
      }
    }
    
    userRating.value = type
    ElMessage.success('感谢您的反馈！')
  } catch (error) {
    ElMessage.error('评价失败，请重试')
  } finally {
    rating.value = false
  }
}

// 分享文章
const shareArticle = async (type) => {
  if (type === 'copy') {
    try {
      await navigator.clipboard.writeText(window.location.href)
      ElMessage.success('链接已复制到剪贴板')
    } catch (error) {
      ElMessage.error('复制失败，请手动复制链接')
    }
  } else if (type === 'email') {
    const subject = encodeURIComponent(`分享文章：${article.value.title}`)
    const body = encodeURIComponent(`我发现了一篇有用的帮助文章，分享给你：\n\n${article.value.title}\n\n${window.location.href}`)
    window.open(`mailto:?subject=${subject}&body=${body}`)
  }
}

// 联系客服
const contactSupport = () => {
  router.push('/chat/support')
}

// 提交反馈
const submitFeedback = () => {
  showFeedbackDialog.value = true
}

// 提交反馈表单
const submitFeedbackForm = async () => {
  try {
    await feedbackFormRef.value.validate()
    submittingFeedback.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('反馈提交成功，感谢您的建议！')
    showFeedbackDialog.value = false
    
    // 重置表单
    feedbackForm.type = ''
    feedbackForm.content = ''
    feedbackForm.contact = ''
  } catch (error) {
    if (error !== 'validation failed') {
      ElMessage.error('提交失败，请重试')
    }
  } finally {
    submittingFeedback.value = false
  }
}

// 查看更多帮助
const viewMoreHelp = () => {
  router.push('/help')
}

// 获取文章数据
const fetchArticle = async () => {
  try {
    loading.value = true
    const articleId = route.params.id
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 模拟文章数据
    const mockArticles = {
      '1': {
        id: '1',
        title: '如何注册和登录账户？',
        summary: '详细介绍账户注册和登录的步骤',
        content: `
          <h3>注册账户</h3>
          <p>1. 打开应用首页，点击"注册"按钮</p>
          <p>2. 输入您的手机号码</p>
          <p>3. 获取并输入验证码</p>
          <p>4. 设置登录密码</p>
          <p>5. 完成注册</p>
          
          <h3>登录账户</h3>
          <p>1. 在登录页面输入手机号和密码</p>
          <p>2. 点击"登录"按钮</p>
          <p>3. 如果忘记密码，可点击"忘记密码"进行重置</p>
          
          <h3>常见问题</h3>
          <p><strong>Q: 收不到验证码怎么办？</strong></p>
          <p>A: 请检查手机号是否正确，或稍后重试。如仍有问题请联系客服。</p>
        `,
        category: '账户问题',
        viewCount: 1234,
        helpfulCount: 45,
        unhelpfulCount: 3,
        createdAt: '2024-01-01 10:00:00',
        updatedAt: '2024-01-15 14:30:00'
      },
      '2': {
        id: '2',
        title: '如何下单预约服务？',
        summary: '从选择服务到完成下单的完整流程',
        content: `
          <h3>选择服务</h3>
          <p>1. 在首页浏览服务分类</p>
          <p>2. 选择您需要的服务类型</p>
          <p>3. 查看服务详情和价格</p>
          
          <h3>预约下单</h3>
          <p>1. 选择服务时间</p>
          <p>2. 填写服务地址</p>
          <p>3. 添加特殊要求（可选）</p>
          <p>4. 确认订单信息</p>
          <p>5. 选择支付方式并完成支付</p>
          
          <h3>注意事项</h3>
          <p>• 请确保地址信息准确无误</p>
          <p>• 建议提前预约，避免高峰期排队</p>
          <p>• 如需要特殊服务，请在备注中说明</p>
        `,
        category: '订单问题',
        viewCount: 856,
        helpfulCount: 32,
        unhelpfulCount: 1,
        createdAt: '2024-01-02 09:00:00',
        updatedAt: '2024-01-20 16:00:00'
      }
    }
    
    const articleData = mockArticles[articleId] || {
      id: articleId,
      title: '帮助文章',
      content: '<p>文章内容加载中...</p>',
      category: '其他问题',
      viewCount: 0,
      helpfulCount: 0,
      unhelpfulCount: 0,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString()
    }
    
    article.value = articleData
    
    // 获取相关文章
    relatedArticles.value = Object.values(mockArticles)
      .filter(item => item.id !== articleId)
      .slice(0, 3)
    
  } catch (error) {
    ElMessage.error('加载文章失败')
    console.error('获取文章失败:', error)
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchArticle()
})
</script>

<style scoped>
.help-detail {
  min-height: calc(100vh - 120px);
  padding: 20px 0;
  background: #f8f9fa;
}

.container {
  max-width: 900px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.breadcrumb {
  flex: 1;
  margin-left: 20px;
}

.placeholder {
  width: 32px;
}

.article-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.article-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.article-header {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 20px;
  margin-bottom: 30px;
}

.article-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
  font-size: 14px;
  color: #999;
}

.article-title {
  font-size: 2rem;
  color: #333;
  margin-bottom: 15px;
  line-height: 1.4;
}

.article-summary {
  color: #666;
  font-size: 1.1rem;
  line-height: 1.6;
}

.article-content {
  color: #333;
  line-height: 1.8;
  margin-bottom: 40px;
}

.article-content :deep(h3) {
  color: #409eff;
  margin: 25px 0 15px 0;
  font-size: 1.3rem;
}

.article-content :deep(p) {
  margin-bottom: 15px;
}

.article-content :deep(strong) {
  color: #333;
  font-weight: 600;
}

.article-footer {
  border-top: 1px solid #f0f0f0;
  padding-top: 30px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 40px;
}

.rating-section h4,
.share-section h4 {
  margin-bottom: 15px;
  color: #333;
  font-size: 1.1rem;
}

.rating-buttons,
.share-buttons {
  display: flex;
  gap: 10px;
}

.related-articles,
.feedback-card {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.related-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.related-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.related-item:hover {
  border-color: #409eff;
  background: #f0f7ff;
}

.related-content {
  flex: 1;
}

.related-content h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 1rem;
}

.related-content p {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 0.9rem;
  line-height: 1.4;
}

.related-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 0.8rem;
  color: #999;
}

.related-arrow {
  color: #409eff;
  margin-left: 15px;
}

.feedback-content p {
  margin-bottom: 20px;
  color: #666;
  line-height: 1.6;
}

.feedback-actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .breadcrumb {
    margin-left: 0;
  }

  .placeholder {
    display: none;
  }

  .article-title {
    font-size: 1.5rem;
  }

  .article-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .article-footer {
    grid-template-columns: 1fr;
    gap: 20px;
  }

  .rating-buttons,
  .share-buttons,
  .feedback-actions {
    flex-direction: column;
  }

  .related-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .related-arrow {
    align-self: flex-end;
    margin-left: 0;
  }
}
</style> 